package com.imooc.sm.global;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


//核心控制器,控制请求路径跳转
public class DispatcherServlet extends GenericServlet {

    private  ApplicationContext context ;

    //每次请求只加载一次IOC容器，加载一次spring.xml ,
    public void init() throws ServletException {
        super.init();
        context =new ClassPathXmlApplicationContext("spring.xml");

    }
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;


        System.out.println("核心过滤器执行");
        /**
         * 前台的请求分两种  1 /staff/add.do   -> staffController  -> add();
         *                2 /login.do       -> selfController   -> login();
         */

        //得到请求路径
        String path = request.getServletPath().substring(1);
        String beanName = null;
        String methodName = null;

        //区分请求种类 staff/add.do    login.do
        int index = path.indexOf("/");
        //staff/add.do
        if (index != -1){

            beanName = path.substring(0,index)+"Controller";             // staffController
            methodName = path.substring(index+1,path.indexOf(".do"));    // add
            System.out.println("是基本事务请求....."+beanName+"....."+methodName);

        }else{
            beanName = "selfController";                                 // selfController
            methodName = path.substring(0,path.indexOf(".do"));          // login
            System.out.println("是self事务请求....."+beanName+"....."+methodName);

        }

        //反射
        Object obj = context.getBean(beanName);

        try {
            Method method = obj.getClass().getMethod(methodName,HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(obj,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}
